package org.yan.stock.server.util;

import java.math.BigDecimal;
import java.text.NumberFormat;

public abstract class MathUtil {
	
	public static final int CALC_SCALE1 = 2;
	public static final int CALC_SCALE2 = 4;
	public static final int CALC_SCALE3 = 6;
	
	public static final NumberFormat nf = NumberFormat.getPercentInstance();

	/**
	 * Calculate a percent value of (b-a)/a
	 * @param a
	 * @param b
	 * @param n
	 * @return
	 */
	public static double calcPerc(String a, String b, int n) {
		double t = Double.valueOf(b) - Double.valueOf(a);
		return new BigDecimal(t).divide(new BigDecimal(a), BigDecimal.ROUND_HALF_UP, n).doubleValue();
	}
	
	/**
	 * Calculate a percent value of (b-a)/a, convert the result to string
	 * @param a
	 * @param b
	 * @param n
	 * @return
	 */
	public static String calcPerc2S(String a, String b, int n) {
		double c = calcPerc(a, b, n);
		return perc2Str(c);
	}
	
	/**
	 * convert a double percent to string with n decimal places reserved
	 * @param base
	 * @param n
	 * @return
	 */
	public static String perc2Str(double base, int n) {
		nf.setMaximumFractionDigits(n); //设置允许的最大小数位
		nf.setMinimumFractionDigits(n); //设置允许的最小小数位
		return nf.format(Math.abs(base));
	}
	
	/**
	 * convert a double percent to string with 2 decimal places reserved
	 * @param base
	 * @return
	 */
	public static String perc2Str(double base) {
		return perc2Str(base, 2);
	}
	
	public static void main(String[] args) {
		System.out.println(calcPerc("27.25","26.91", 4));
		System.out.println(perc2Str(-0.0125));
	}
}
